package com.beici.waterghost.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beici.waterghost.mapper.collentMapper;
import com.beici.waterghost.mapper.nodeMapper;
import com.beici.waterghost.model.collent;
import com.beici.waterghost.model.node;
import com.beici.waterghost.model.resultes;
import com.beici.waterghost.service.collentService;
import com.beici.waterghost.utils.takeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class collentServiceImpl implements collentService {

    @Autowired
    private collentMapper collentServer;
    @Autowired
    private nodeMapper nodeServer;
    @Autowired
    private nodeServiceImpl nodeService;
    @Override
    @Transactional
    public resultes collentOrEscNode(Integer userId, Long nodeId, Integer state) {
        node n = nodeServer.selectOne(new QueryWrapper<node>().eq("node_id",nodeId).select("node_id,node_like,user_id"));
        // 查询该帖子是否允许收藏
        if (n.getNodeLike()<0){
            return resultes.error("该帖子已经关闭收藏功能");
        }else if (n.getUserId()==userId){
            return resultes.error("自己的帖子无法收藏");
        }
        n.setNodeId(nodeId);
        n.setNodeLike(n.getNodeLike()+state);
        nodeServer.updateById(n);
        collent c = new collent(userId,nodeId,new Date());
        if (state<0){
            // 取消
            collentServer.delete(new QueryWrapper<collent>().eq("user_id",userId).eq("node_id",nodeId));
        }else {
            takeUtils.vefitiyINSERT(collentServer.insert(c));
        }
        return resultes.success("操作成功",true);
    }

    @Override
    public resultes userCollentNodes(Integer userId) {
        List<collent> collents = collentServer.selectList(new QueryWrapper<collent>().eq("user_id", userId).select("node_id"));
        List<node> nodes = new ArrayList<>();
        for (collent collent : collents) {
            resultes resultes = nodeService.quertyNode(collent.getNodeId());
            node data = (node) resultes.getData();
            data.setCollentState(false);
            nodes.add(data);
        }
        return resultes.success("获取成功",nodes);
    }

    // 判断用户是否收藏
    public boolean userCollentNode(Long nodeId,Integer userId){
        Integer integer = collentServer.selectCount(new QueryWrapper<collent>().eq("node_id", nodeId).eq("user_id", userId));
        return integer>0?true:false;
    }
}
